//
//  SSUserOrderViewController.swift
//  拾舍清洁
//
//  Created by sky.wei on 2023/2/28.
//

import UIKit

import SwiftyJSON


class SSUserOrderViewController: SSBaseUserOrderController {
    
    var address: SSAddress = SSAddress()
    var headerView = SSUserOrderHeaderView()
    var footerView = SSUserOrderFooterView()
    var listItem: Array<ListCombo> = []
    var serviceType = ""
    var orderLimit = SSOrderLimit()
    var totalTempPrice : Float = 0//临时总价格
    var couponFee : Float = 0.0//优惠券价格
    var startingFee : String = "0"//起步费
    
    
    @IBOutlet weak var shopingCart: SSShopingCartTool!
    @IBOutlet weak var tableView: UITableView!
    
    override func viewDidLoad() {
        super.viewDidLoad()
        
        title = "提交订单"
        
        shopingCart.btn.setTitle("提交订单", for: .normal)
        shopingCart.delegate = self

        let headerView = SSUserOrderHeaderView.headerView()
//        headerView.frame = CGRect(x: 0, y: 0, width: UIScreen.main.bounds.width, height: 116 + 12 + 24 + 45 + 36 + 40)
        self.headerView = headerView
        tableView.tableHeaderView = headerView
        
        let footerView = SSUserOrderFooterView.footerView()
//        footerView.frame = CGRect(x: 0, y: 0, width: UIScreen.main.bounds.width, height: 330)
        footerView.totalPrice = shopingCart.totalPrice
        footerView.setData()
        footerView.couponClosure { number in
//            let price = self.shopingCart.totalPrice - stringToFloat(str: number.money)
//            self.shopingCart.priceLab.text = "\(price)"
            self.couponFee = stringToFloat(str: number.money)
            self.handleThresholdFee()
        }
        self.footerView = footerView
        tableView.tableFooterView = footerView
        
        tableView.register(UINib(nibName: "SSUserOrderCell", bundle: Bundle.init(for: SSUserOrderCell.self)), forCellReuseIdentifier: "SSUserOrderCell")
        tableView.delegate = self
        tableView.dataSource = self
        tableView.separatorStyle = .none
        
        
        
        getListNetwork()
        
        getItemInfo()
        
        getLimitInfo()
        
    }
    
    override func viewDidLayoutSubviews() {
        super.viewDidLayoutSubviews()
        self.headerView.frame = CGRect(x: 0, y: 0, width: UIScreen.main.bounds.width, height: 150 + 20)
        footerView.frame = CGRect(x: 0, y: 0, width: UIScreen.main.bounds.width, height: 330)

    }

    //获取本地订单数据
    func getItemInfo() {
        let list = getOrderData()
        var listCombos: Array<Any> = []
        for dic in list {
            let orders = dic["items"] as! Array<Dictionary<String,AnyObject>>
            for order in orders{
                let item = ListCombo()
                item.id = order["id"] as! String
                item.name = order["name"] as! String
                item.fee = order["fee"] as! String
                item.imgUrl = order["imgUrl"] as! String
                item.rootName = order["rootName"] as! String
                item.totalFee = order["totalFee"] as? Float ?? 0
                var specs:Array<SSSpec> = []
                if let listSpecs = order["listSpecs"] as? Array<Dictionary<String, Any>>
                {
                    for subDic in listSpecs {
                        let item = SSSpec()
                        item.id = subDic["id"] as! String
                        item.name = subDic["name"] as! String
                        item.fee = subDic["fee"] as! String
                        specs.append(item)
                    }
                }
                item.specs = specs
                listCombos.append(item)
            }
        }
        self.listItem = listCombos as! Array<ListCombo>
        let name = self.listItem.first?.rootName
        if (name == "日常清洁"){
            serviceType = "1"
        }else if (name == "退房清洁"){
            serviceType = "2"
        }else if (name == "深度清洁"){
            serviceType = "3"
        }else if (name == "蒸汽地毯"){
            serviceType = "4"
        }else{
            serviceType = "1"
        }
        headerView.serviceType = serviceType
    }
  
    func handleThresholdFee() {
        if(self.shopingCart.totalPrice < self.orderLimit.startingAmount){//有起步费
            self.footerView.thresholdFeeLab.text = "$\(self.orderLimit.startingFee)"
            self.footerView.threshsholdDesLab.isHidden = false
            self.footerView.threshsholdDesLab.text = orderLimit.startingMsg
            totalTempPrice = self.shopingCart.totalPrice + self.orderLimit.startingFee
            startingFee = "\(self.orderLimit.startingFee)"
        }else{//无起步费
            totalTempPrice = self.shopingCart.totalPrice
            self.footerView.thresholdFeeLab.text = "免上门费"
            self.footerView.threshsholdDesLab.isHidden = true
            startingFee = "0"
        }
        totalTempPrice = totalTempPrice - self.couponFee
        self.footerView.jianLab.text = "总优惠 $\(self.couponFee)"
        self.footerView.totalLab.text = "总计 $\(totalTempPrice)"
        self.shopingCart.priceLab.text = "$\(totalTempPrice)"
        
        let string2 = self.footerView.jianLab.text
        let attributedString2 = NSMutableAttributedString(string:string2 ?? "")
        attributedString2.addAttribute(NSAttributedString.Key.foregroundColor, value: UIColor.init(hex: "#FC4242")!, range: NSRange(location: 3, length: string2!.count - 3))
        self.footerView.jianLab.attributedText = attributedString2
        
        let string = self.footerView.totalLab.text
        let attributedString = NSMutableAttributedString(string:string ?? "")
        attributedString.addAttribute(NSAttributedString.Key.foregroundColor, value: UIColor.init(hex: "#FC4242")!, range: NSRange(location: 2, length: string!.count - 2))
        self.footerView.totalLab.attributedText = attributedString

    }

}




extension SSUserOrderViewController {
    
    func getLimitInfo() {
        SSProgressHUD.share.show()
        HttpConnectTools.share.request(urlString: APIUrl.share.getOrderLimit_URL, parameters: nil) { (result, error) in
            SSProgressHUD.share.dismiss()
            if let _ = result{
                let json = JSON(parseJSON: result!)
                let retCode = json["retCode"].stringValue
                if(retCode == "0000"){
                    self.orderLimit = SSOrderLimit.deserialize(from: result, designatedPath: "data") ?? SSOrderLimit()
                    debugPrint(self.orderLimit.toJSON() as Any)
                    self.handleThresholdFee()
                }
            }
        }
    }
    
    
    func getListNetwork() {
        let param = [
                    "phoneNo": kUserPhone
        ] as [String:AnyObject]
        SSProgressHUD.share.show()
        HttpConnectTools.share.request(urlString: APIUrl.share.getUserAddress_URL, parameters: param) { (result, error) in
            SSProgressHUD.share.dismiss()
            if let _ = result{
                
                var addresses: Array<SSAddress> = []

                if let items = [SSAddress].deserialize(from: result, designatedPath: "data.listAddress"){
                    items.forEach {
                        addresses.append($0!)
                    }
                }
                if addresses.count>0 {
                    self.address = addresses.first!
                }
                self.headerView.setData(address: self.address)
                
                print("")
            }else{
//                if let message = error?.userInfo["errorinfo"]{
//                    self.view.makeToast(message as? String)
//                }
            }
        }
    }
  
    
    //MARK: -network
    func userOrderRequest() {

//        let price = shopingCart.totalPrice - stringToFloat(str: footerView.coupon.money)
        //地址、时间
        var params = [
            "contact": headerView.address.contact,
            "contactPhone": headerView.address.contactPhone,
            "houseNo": headerView.address.contact,
            "phoneNo": kUserPhone,
            "serviceAddr": headerView.address.address,
            "zip": headerView.address.zip,
            "serviceType": serviceType,
            "serviceTime": headerView.selectedDate,
            "duration": headerView.selectedTimeSection,
            "total": "\(totalTempPrice)",
            "note": footerView.textView.text ?? "",
            "startingFee": startingFee,
                ] as! [String:AnyObject]
    
        //优惠券
        if footerView.coupon.userCouponId.count > 0 {
            params["couponId"] = footerView.coupon.couponId as AnyObject
            params["userCouponId"] = footerView.coupon.userCouponId as AnyObject
            params["couponMoney"] = footerView.coupon.money as AnyObject
        }
        
        //公共规格
        for (i, item) in headerView.specses.enumerated() {
            if i == 0 {
                params["isMonth"] = item.name as AnyObject
            }
            if i == 1 {
                params["isSpace"] = item.name as AnyObject
            }
            if i == 2 {
                params["isPet"] = item.name as AnyObject
            }
            print("---公用规格\(item.name)\(i)")
        }

        
        var items:Array<Any> = []
        for item in listItem {
            var dic = [
                "rootName": item.rootName,
                "itemFee": item.fee,
                "itemId": item.id,
                "itemName": item.name,
                "itemTotal":item.totalFee
            ] as [String : Any]
            var listSpecs:Array<Any> = []
            for item in item.specs {
                let spec = [
                    "specsFee": item.fee,
                    "specsId": item.id,
                    "specsName": item.name
                ]
                listSpecs.append(spec)
            }
            dic["listSpecs"] = listSpecs
            items.append(dic)
        }
        
        params["listOrder"] = items as AnyObject
        
        debugPrint("项目==",jhToJson(params))
        
        SSProgressHUD.share.show()
        HttpConnectTools.share.request(urlString: APIUrl.share.userOrderNew, parameters: params) { (result, error) in
            SSProgressHUD.share.dismiss()
            if let _ = result{
                let json = JSON(parseJSON: result!)
                let retCode = json["retCode"].stringValue
                let retMsg = json["retMsg"].stringValue
                if(retCode == "0000"){
                    let view = SSUserOrderDoneView.orderDoneView()
                    view.resultClosure {
                        self.navigationController?.popToRootViewController(animated: true)
                    }
                    kUserDefaults.removeObject(forKey: kShopingCartKey)
                    kUserDefaults.removeObject(forKey: kShopingCartFee)
                }else{
                    dissmissToTast(msg: retMsg)
                }
            }else{
//                if let message = error?.userInfo["errorinfo"]{
//                    self.view.makeToast(message as? String)
//                }
            }
        }
    }
}


extension SSUserOrderViewController:SSCartToolDelegate{
    func cartResult() {
        
        if self.shopingCart.totalPrice == 0 {
            view.makeToast("请先选择产品")
            return
        }
        
        if(shopingCart.totalPrice < self.orderLimit.thresholdAmount){
            let alertView = SSAlertView(message: self.orderLimit.thresholdMsg, confirmTitle: "确定")
                alertView.showAlert(confirm:  {
                }) {
                }
            return
        }
        
        if(self.footerView.coupon.couponId.count > 0){
            if(shopingCart.totalPrice < stringToFloat(str:footerView.coupon.fullMoney)){
                view.makeToast("金额不足不能使用优惠券！")
                return
            }
        }
        if self.headerView.address.contactPhone.count == 0 {
            view.makeToast("请选择地址")
            return
        }
        if (self.headerView.serviceTimeLab.text == "请选择到达时间") {
            view.makeToast("请选择到达时间")
            return
        }
        if self.headerView.specses.count == 0 {
            view.makeToast("请选择规格")
            return
        }
        userOrderRequest()
    }
}

extension SSUserOrderViewController: UITableViewDelegate, UITableViewDataSource
{
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return self.listItem.count
    }
    
    func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        
    }
    func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat {
        return 42
    }

    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell = tableView.dequeueReusableCell(withIdentifier: "SSUserOrderCell") as! SSUserOrderCell
        cell.setData(model: self.listItem[indexPath.row])
        return cell
    }
    
    func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
        return 55 + 12
    }
    
    //返回每一个行对应的事件按钮
    func tableView(_ tableView: UITableView, editActionsForRowAt indexPath: IndexPath)
        -> [UITableViewRowAction]? {
            //创建“删除”事件按钮
            let delete = UITableViewRowAction(style: .normal, title: "删除") {
                action, index in
//                reduceData(id: self.listItem[index.row].id)
                reduceOrder(id: self.listItem[index.row].id)
                //将对应条目的数据删除
                self.listItem.remove(at: index.row)
                tableView.reloadData()
                self.footerView.totalPrice = self.shopingCart.totalPrice
//                self.footerView.setData()
                self.handleThresholdFee()
            }
            delete.backgroundColor = UIColor.red
             
            //返回所有的事件按钮
            return [delete]
    }
    
    
}
